<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="电影名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入电影名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="电影分类" prop="fileType">
          <el-select v-model="queryParams.fileType" placeholder="请选择内容分类" @change="changeTvType">
            <el-option v-for="item in tvTypeOptions" :key="item.id" :label="item.name" :value="item.id"  :disabled="item.status == 1"></el-option>
            </el-select>
      </el-form-item> -->
      <el-form-item label="电影类型" prop="typeData">
        <el-select v-model="queryParams.typeData" placeholder="请选择电影类型">
            <el-option v-for="item in tvDataOptions" :key="item.id" :label="item.name" :value="item.id" :disabled="item.status == 1"></el-option>
            </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
                <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
              </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:data:add']"
        >导入电影</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:data:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="电影名称" align="center" prop="title" />
      <!-- <el-table-column label="电影分类" align="center" prop="fileTypeStr" /> -->
      <el-table-column label="电影类型" align="center" prop="typeDataStr" />
      <el-table-column label="海报图片" align="center" prop="imgAddress" >
        <template slot-scope="scope">
          <img v-bind:src="scope.row.imgAddress" class="img-lg" />
        </template>
      </el-table-column>
      <el-table-column label="播放地址" align="center" prop="urlAddress" />
      <el-table-column label="是否推荐" align="center" prop="isRecommend" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_video_recommend" :value="scope.row.isRecommend"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:data:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row,scope.index)"
            v-hasPermi="['system:data:query']"
          >详细</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <el-dialog :title="title" :visible.sync="openAdd" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件目录">
          <el-tree
      style="max-width: 600px"
      :data="treeData"
      :props="treeProps"
      :load="loadNode"
      lazy
      show-checkbox
      ref="tree"
    ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitData">确 定</el-button>
        <el-button @click="cancelData">取 消</el-button>
      </div>

     
    </el-dialog>

         <!-- 上传完成提示框 -->
         <el-dialog :title="uploadSuccessTitle" :visible.sync="uploadSuccessVisible" width="500px" append-to-body>
      <div>文件上传完成,请到内容管理模块查看文件上传记录</div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeUploadSuccessDialog()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="titleDetail" :visible.sync="openDetail" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
        <el-form-item label="电影名称" prop="title">{{ form.title }}
        </el-form-item>
</el-col>
         <el-col :span="12">
          <el-form-item label="是否推荐" >
          <div v-if="form.isRecommend == 0">不推荐</div>
          <div v-else-if="form.isRecommend == 1">推荐</div>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="电影类型" prop="typeData">{{ form.typeDataStr }}
        </el-form-item>
        </el-col>
      <el-col :span="24">
        <el-form-item label="播放地址" prop="urlAddress">{{ form.urlAddress }}
        </el-form-item>
        </el-col>
        <el-col :span="24">
        <el-form-item label="海报图片" prop="imgAddress">{{ form.imgAddress }}
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="推荐图片" prop="recommendBanner">{{ form.recommendBanner }}
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="描述" prop="description">{{ form.description }}
        </el-form-item>
        </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button  @click="closeDetail">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listData, getData, delData, addData, updateData } from "@/api/system/data";
import { checkUsb,getFileData,getFileDataByPath,getContentType,getContentTypeData } from '@/api/index';
import { getToken } from "@/utils/auth";
import axios from "axios";

export default {
  name: "Data",
  dicts: ['sys_video_recommend', 'sys_user_sex'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 内容列表表格数据
      dataList: [],
       // 内容分类选项
       tvTypeOptions: [],
      // 内容分类的类型详情选项
      tvDataOptions: [],
      // 日期范围
      dateRange: [],
      // 弹出层标题
      title: "",
      titleDetail: "内容详情",
      // 是否显示弹出层
      open: false,
      openDetail: false,
      openAdd:false,
      // 上传完成提示框相关属性
      uploadSuccessTitle: "上传完成",
      uploadSuccessVisible: false,
      startUploadUrl: process.env.VUE_APP_BASE_API + "/api/startUpload2", // 选中文件上传地址
      uploadProgressUrl: process.env.VUE_APP_BASE_API + "/api/uploadProgress2/", // 文件上传进度请求地址
      contentFileUrl: process.env.VUE_APP_BASE_API + "/api/contentFileData2", // 获取上传文件数据地址
      // 版本号
      version: "3.8.9",
      timer: null, // 定时器变量
      numberRow: 2,
      treeData: [],
      treeProps: {
        label: 'name',
        children: 'children',
        isLeaf: 'leaf',
      },
      uploadProgress: -1,//上传进度
      uploadTaskId: null, // 用于存储后端返回的上传任务ID
      timer: null, // 用于存储定时器ID
      selectedFiles: [], // 用于存储选中目录下的文件
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        fileType: 1,//电影类型
        typeData: null,
        urlAddress: null,
        number: null,
        taskId: null,
        userName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    // this.getContentType();
    this.getList();
    this.getContentTypeData({
          "typeId": this.queryParams.fileType,
         });
  },
  methods: {
    loadNode(node, resolve) {
      console.log("loadNode: "+node+"============"+node.level);
      //获取内容分类配置和剧情类型详情
      if (node.level === 0) {
        // 根节点请求后端获取数据
        getFileData().then(response => {
          resolve(response.data);
        });
      } else {
        console.log("模拟数据");
        const selectedNodeResultData = node.data;
        console.log("selectedNodeResultData: "+JSON.stringify(selectedNodeResultData));
        if (selectedNodeResultData &&!selectedNodeResultData.leaf) {
          const path = selectedNodeResultData.path;
          console.log("path: "+path);
          getFileDataByPath(path).then(response => {
            const children = response.data;
            resolve(children);
          });
        } else {
          resolve([]);
        }
      }
    },
    closeUploadSuccessDialog() {
      this.uploadSuccessVisible = false; // 隐藏上传完成提示框
    },
    submitData: function (){
      this.$refs["form"].validate(valid => {
        console.log("============提交校验:"+valid+"=======&&&&&&&&&&==="+JSON.stringify(this.form));
        if (valid) {
          const checkedNodes = this.$refs.tree.getCheckedNodes();
      console.log("提交信息 checkedNodes : "+JSON.stringify(checkedNodes));
      const filePaths = checkedNodes.map(node => node.path);
      console.log("提取需要上传的文件信息:"+JSON.stringify(filePaths)+"========"+filePaths.length);
      if(filePaths.length == 0){
        this.$modal.msgError("请选择上传的文件");
        return;
      }
      this.openAdd = false;
      // this.$refs["form"].validate(valid => {
        const token = getToken();
        console.log("formData: "+JSON.stringify(filePaths)+"======="+this.form);
        var data = {
          filePaths:filePaths,
          // videoType:this.form.videoType,
          plotType:this.form.plotType,
        };
        console.log("提交数据: "+JSON.stringify(data));
        // axios.post('/dev-api/api/startUpload', data , {
        axios.post(this.startUploadUrl, data , {
          headers: {
            'Authorization': `Bearer `+token, // 假设 token 是你获取到的认证令牌
          },
        }).then(response => {
            var code = response.data.code;
            console.log("文件上传响应: "+JSON.stringify(response.data)+"==================code:"+code);
            if(code == 200){
              this.uploadTaskId = response.data.data;
              document.body.style.overflow = 'hidden'; // 禁用页面滚动
              this.timer = setInterval(() => {
                console.log("启动定时器");
                this.getUploadProgress();
              }, 1000);
            }else{
                this.$modal.msgError(JSON.stringify(response.data.msg));
                this.uploadProgress = -1;
            }
        }).catch(error => {
            console.error('上传失败', error);
            this.uploadProgress = -1;
        });
      // });


        }
      });

    },
    cancelData: function(){
      console.log("文件上传取消");
      this.openAdd = false;
      this.reset();
    },



    /** 查询内容列表列表 */
    getList() {
      this.loading = true;
      listData(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    closeDetail(){
      this.openDetail = false;
    },
    /** 详细按钮操作 */
    handleView(row) {
      this.openDetail = true;
      this.form = row;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        fileType: 1,
        typeData: null,
        urlAddress: null,
        createTime: null,
        number: null,
        taskId: null,
        userName: null
      };
      this.resetForm("form");
    },
    changeTvType(data){
      this.plotType = null;
      this.tvDataOptions = null;
      this.getContentTypeData({
          "type": data,
        });
    },
    getContentType(){
      getContentType().then(response =>{
        this.tvTypeOptions = response.data;
        if(this.queryParams.fileType !== null){
          this.getContentTypeData({
          "type": this.queryParams.fileType,
         });
        }
     
      }).catch(error => {
        console.log("获取内容分类的响应:"+error);
        return
      });

    },

    getContentTypeData(data){
      getContentTypeData(data).then(response =>{
        this.tvDataOptions = response.data;
        }).catch(error => {
          console.log("获取内容分类的类型详情响应:"+error);
          return
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
      this.tvDataOptions = null;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // this.open = true;
      this.openAdd = true;
      this.title = "添加内容列表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getData(id).then(response => {
        this.form = response.data;
        this.tvDataOptions = response.tvDatas;
        this.tvTypeOptions = response.tvTypes;
        this.open = true;
        this.title = "修改内容列表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateData(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addData(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除内容列表编号为"' + ids + '"的数据项？').then(function() {
        return delData(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/data/export', {
        ...this.queryParams
      }, `data_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
